package com.uduemc.biso.node.web.controller;

import cn.hutool.core.util.StrUtil;
import com.uduemc.biso.core.extities.center.Agent;
import com.uduemc.biso.core.extities.center.AgentLoginDomain;
import com.uduemc.biso.core.extities.center.Host;
import com.uduemc.biso.core.extities.center.SysComponentType;
import com.uduemc.biso.core.utils.AgentLinkUtil;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.core.entities.*;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.web.ajax.component.ComponentFormValid;
import com.uduemc.biso.node.web.ajax.component.inter.AVComponentUdin;
import com.uduemc.biso.node.web.ajax.pojo.FormSubmit;
import com.uduemc.biso.node.web.ajax.pojo.formsubmit.FormSubmitData;
import com.uduemc.biso.node.web.component.RequestHolder;
import com.uduemc.biso.node.web.service.byfeign.*;
import com.uduemc.biso.node.web.utils.EmailUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class AjaxFormInfoController {

    @Resource
    private ContainerService containerServiceImpl;

    @Resource
    private ComponentService componentServiceImpl;

    @Resource
    private SysStaticDataService sysStaticDataServiceImpl;

    @Resource
    private FormService formServiceImpl;

    @Resource
    private RequestHolder requestHolder;

    @Resource
    private ComponentFormValid componentFormValid;

    @Resource
    private EmailService emailService;

    @Resource
    private AgentService agentServiceImpl;

    @Resource
    private GlobalProperties globalProperties;

    @Resource
    private SystemService systemServiceImpl;

    @PostMapping(value = {"/ajax/forminfo/submit", "/site/*/ajax/forminfo/submit"}, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public JsonResult submit(@RequestBody FormSubmit formSubmit) throws IOException {
        if (formSubmit == null || formSubmit.illegal() == false) {
            // 基本参数信息异常
            return JsonResult.illegal();
        }

        long boxId = formSubmit.getBoxid();
        long systemId = formSubmit.getSystemid();
        long systemItemId = formSubmit.getSystemitemid();
        long formId = formSubmit.getFormid();
        long hostId = requestHolder.getHostId();

        SForm sForm = formServiceImpl.getSFormByHostIdAndId(hostId, formId);
        if (sForm == null || sForm.getHostId() == null || sForm.getHostId() != hostId) {
            return JsonResult.illegal();
        }

        Long sFormHostId = sForm.getHostId();
        Long sFormSiteId = sForm.getSiteId();

        String systemName = "";
        String systemItemName = "";
        if (boxId > 0) {
            SContainerQuoteForm sContainerQuoteForm = containerServiceImpl.getSContainerQuoteFormOkByContainerId(boxId);
            if (sContainerQuoteForm == null || sContainerQuoteForm.getHostId() == null || sContainerQuoteForm.getHostId() != hostId
                    || sContainerQuoteForm.getFormId() == null || sContainerQuoteForm.getFormId() != formId) {
                return JsonResult.illegal();
            }
        } else if (systemId > 0 && systemItemId > 0) {
            SSystem sSystem = systemServiceImpl.findInfo(sFormHostId, sFormSiteId, systemId);
            if (sSystem == null) {
                return JsonResult.illegal();
            }
            systemName = sSystem.getName();
            systemItemName = systemServiceImpl.systemAndItemIdForName(sSystem, systemItemId);
            if (StrUtil.isBlank(systemItemName)) {
                return JsonResult.illegal();
            }
        } else {
            return JsonResult.illegal();
        }

        // 验证提交的组件
        List<SComponentForm> listSComponentForm = componentServiceImpl.getInfosByHostFormIdStatus(hostId, formId, (short) 0);
        if (CollectionUtils.isEmpty(listSComponentForm)) {
            if (CollectionUtils.isEmpty(formSubmit.getData())) {
                // 配置中的提交成功后的提示信息
                String submitSuccessMessage = ComponentFormValid.submitSuccessMessage(null);
                return JsonResult.messageSuccess(submitSuccessMessage);
            } else {
                return JsonResult.illegal();
            }
        }

        List<FormSubmitData> data = formSubmit.getData();
        Iterator<FormSubmitData> iteratorData = data.iterator();
        while (iteratorData.hasNext()) {
            FormSubmitData formSubmitData = iteratorData.next();
            long comid = formSubmitData.getComid();
            List<String> value = formSubmitData.getValue();
            SComponentForm sComponentForm = null;
            for (SComponentForm item : listSComponentForm) {
                if (item != null && item.getId() != null && item.getId() == comid) {
                    sComponentForm = item;
                }
            }
            if (sComponentForm == null) {
                return JsonResult.illegal();
            }

            SysComponentType sysComponentType = sysStaticDataServiceImpl.getComponentTypeInfoById(sComponentForm.getTypeId());
            if (sysComponentType == null) {
                return JsonResult.illegal();
            }
            AVComponentUdin aVComponentUdin = componentFormValid.getAVComponentUdinByName(sysComponentType.getType());
            if (aVComponentUdin == null) {
                return JsonResult.illegal();
            }

            String valid = aVComponentUdin.valid(sComponentForm.getConfig(), value);
            if (StringUtils.hasText(valid)) {
                return JsonResult.messageError(valid);
            }
        }

        SContainerForm sContainerForm = containerServiceImpl.getContainerFormmainboxByHostFormId(hostId, formId);

        if (boxId > 0) {
            // 验证码校验
            if (!formServiceImpl.vcerificationCode(boxId, formId, formSubmit.getCaptcha())) {
                return JsonResult.messageError(ComponentFormValid.submitCaptchValidMessage(sContainerForm));
            }
        } else if (systemId > 0 && systemItemId > 0) {
            if (!formServiceImpl.vcerificationCode(systemId, systemItemId, formId, formSubmit.getCaptcha())) {
                return JsonResult.messageError(ComponentFormValid.submitCaptchValidMessage(sContainerForm));
            }
        }

        SFormInfo sFormInfo = formServiceImpl.insertFormSubmitData(formSubmit, systemName, systemItemName, sForm, listSComponentForm);
        if (sFormInfo == null) {
            return JsonResult.assistance();
        }

        if (boxId > 0) {
            // 删除验证码
            formServiceImpl.delFormCode(boxId, formId);
        } else if (systemId > 0 && systemItemId > 0) {
            // 删除验证码
            formServiceImpl.delFormCode(systemId, systemItemId, formId);
        }

        HConfig hostConfig = requestHolder.getAccessHost().getHostConfig();
        // 添加提醒邮件
        String emailInbox = hostConfig.getEmailInbox();
        if (null == emailInbox) {
            emailInbox = "";
        }
        emailInbox = emailInbox.trim();
        if (hostConfig.getFormEmail() != null && hostConfig.getFormEmail() == 1 && !StringUtils.isEmpty(emailInbox)) {
            String[] emailArr = emailInbox.split(",");

            List<SFormInfoItem> formInfoItemList = new ArrayList<>();
            for (FormSubmitData formSubmitData : data) {
                List<String> value = formSubmitData.getValue();
                if (CollectionUtils.isEmpty(value) || (value.size() > 0 && StringUtils.isEmpty(value.get(0)))) {
                    continue;
                }
                SComponentForm sComponentForm = null;
                for (SComponentForm item : listSComponentForm) {
                    if (item.getId() == formSubmitData.getComid()) {
                        sComponentForm = item;
                    }
                }
                if (sComponentForm == null) {
                    continue;
                }
                String valueStr = "";
                for (String str : value) {
                    valueStr += "," + str;
                }
                SFormInfoItem item = new SFormInfoItem();
                item.setLabel(sComponentForm.getLabel());
                item.setValue(valueStr.substring(1));
                formInfoItemList.add(item);
            }

            Host host = requestHolder.getHost();
            Long agentId = host.getAgentId();
            Agent agent = null;
            AgentLoginDomain agentLoginDomain = null;
            if (agentId != null && agentId.longValue() > 0) {
                agent = agentServiceImpl.agent(agentId);
                agentLoginDomain = agentServiceImpl.agentLoginDomain(agentId);
            }

            String logoimg = "";
            String title = "刺猬响站--网站新表单通知";
            if (agent != null) {
                try {
                    if (agentLoginDomain != null) {
                        logoimg = AgentLinkUtil.agentLogo(agentLoginDomain);
                    }
                } catch (Exception e) {
                }

                if (StrUtil.isNotBlank(agent.getName())) {
                    title = agent.getName() + "--网站新表单通知";
                } else {
                    title = "网站新表单通知";
                }
            }
            if (StrUtil.isBlank(logoimg)) {
                logoimg = "https://bisostatic.35.cn/site/assets/formemail/mail1.jpg";
            }

            List<SEmail> emailList = new ArrayList<>();
            Map<String, Object> mapData = new HashMap<>();
            DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
            mapData.put("dateTime", dateFormat.format(sFormInfo.getCreateAt()));
            mapData.put("formName", sForm.getName());
            mapData.put("infoList", formInfoItemList);
            mapData.put("logoimg", logoimg);
            mapData.put("title", title);
            mapData.put("agent", agent);
            String mailBody = EmailUtil.generateFormMailBody(mapData);
            for (String emailAddress : emailArr) {
                if (StringUtils.isEmpty(emailAddress.trim())) {
                    continue;
                }
                SEmail sEmail = new SEmail();
                sEmail.setHostId(sForm.getHostId());
                sEmail.setSiteId(sForm.getSiteId());
                sEmail.setMailType(EmailUtil.MAIL_TYPE_FORM_EMAIL);
                sEmail.setMailFrom(EmailUtil.MAIL_FROM);
                sEmail.setMailFromName(globalProperties.getSite().getMailFromname());
                sEmail.setMailTo(emailAddress);
                sEmail.setMailSubject(title);
                sEmail.setMailBody(mailBody);
                sEmail.setSend(0);
                sEmail.setSendAt(new Date());
                emailList.add(sEmail);
            }
            if (emailList.size() > 0) {
                List<SEmail> sEmailList = emailService.insert(emailList);
                EmailUtil.addMailQueue(sEmailList);
            }
        }

        // 配置中的提交成功后的提示信息
        String submitSuccessMessage = ComponentFormValid.submitSuccessMessage(sContainerForm);
        return JsonResult.messageSuccess(submitSuccessMessage);
    }
}